﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace MaciejGrabek.WebAPITools
{
    public static class JsonSerializationHelper
    {
        public static string Serialize<T>(T item)
        {
            byte[] json = new byte[] { };
            using (MemoryStream ms = new MemoryStream())
            {
                DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T));
                s.WriteObject(ms, item);
                json = ms.ToArray();
            }
            return Encoding.UTF8.GetString(json, 0, json.Length);
        }

        public static T Deserialize<T>(string jsonString)
        {
            byte[] data = Encoding.UTF8.GetBytes(jsonString);
            MemoryStream memStream = new MemoryStream(data);
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T item = (T)serializer.ReadObject(memStream);
            return item;
        }

        public static T Deserialize<T>(Stream jsonStream)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T item = (T)serializer.ReadObject(jsonStream);
            return item;
        }
    }
}
